<!--
 作者：ex_wangshuai
 日期：2016-11-08
 功能：首页-掌天下-品类竞争分析_产品竞争分析
 参数：
 事件：
-->
<template>
  <div class="competitionAnalysis">
    <div class="loading-box">
      <img src="../../../../static/img/loading.gif" class="loading">
    </div>
    <toolbar :view-title="viewTitle">
      <div class="leftButton" type="button" @click="this.$broadcast('goBack')" slot="left-button">&nbsp;</div>
      <div class="rightButton"
           type="button"
           slot='right-button'>
        <div class="filterButton" @click="showFilter" v-show="!filterOpenState">
          <span class="filterIcon" :page-id="routeKey">&nbsp;</span>
          <span>筛选</span>
        </div>
        <div class="menuButton" @click="showSlideMenu" v-show="!filterOpenState">
          <span class="menuIcon">&nbsp;</span>
          <span>菜单</span>
        </div>
        <span v-show="filterOpenState" @click="doFilter" class="filterOver">完成</span>
      </div>
    </toolbar>
    <div class="filter-message-box clearfix">
      <a class="filter-condition" @click="showFilter('pinlei')" href="javascript:;">{{pinlei}}</a>
      <a class="filter-condition" @click="showFilter('pinpai')" href="javascript:;">{{pinpai}}</a>
      <a class="filter-condition" @click="showFilter('pingtai')" href="javascript:;">{{pingtai}}</a>
      <a v-if="startTime" class="filter-condition" @click="showFilter('shijian')" href="javascript:;">{{startTime | timeFilter}} - {{endTime | timeFilter}}</a>
    </div>
    <div class="competition-analysis-content">
      <div class="slide" v-for="chart in charts">
        <div class="title-time">
          <p class="title">{{chart.subTitle}}</p>
        </div>
        <div v-if="chart.detail.length">
          <div v-for="item in chart.message" class="important">
            {{item}}
          </div>
        </div>
        <div class="chartContainer chartContainer{{$index}}" v-show="chart.detail.length">
        </div>
        <div class="item-data" v-if="!chart.detail.length">
          暂无数据
        </div>
        <div class="division{{$index}}"></div>
      </div>
    </div>
    <page-turning :mkey="routeKey" :page-id="'industry'">
    </page-turning>
    <slide-list v-if="showList">
    </slide-list>
    <filter-view v-show="filterOpenState"
                 :default-org-id="defaultOrgId"
                 :default-category="defaultCategory"
                 :default-category-id="defaultCategoryId"
                 :choose-platforms= "pingtai"
                 :choose-platforms-id= "pingtaiId"
                 :page-id="routeKey"
                 :filter-button = "filterButton"
                 :default-start-date="startTime"
                 :default-end-date="endTime">
    </filter-view>
    <confirm :show.sync="timeoutStatus"
             title="加载失败,您可以"
             cancel-text="返回首页"
             confirm-text="重新加载"
             @on-cancel="this.$route.router.go('/home')"
             @on-confirm="reload">
    </confirm>
    <confirm :show.sync="show" title="是否退出？" cancel-text="取消" confirm-text="确定" @on-confirm="onAction('确认')"></confirm>
  </div>
</template>

<script>
  // import Echarts from 'echarts/lib/echarts.js'
  import 'echarts/lib/component/legend'
  import 'echarts/lib/component/tooltip'
  import 'echarts/lib/chart/bar'
  import Toolbar from '../../common/Toolbar.vue'
  import pageTurning from '../../common/pageTurning.vue'
  import slideList from '../list/slideList.vue'
  import FilterView from '../../common/FilterView.vue'
  import Confirm from 'vux/dist/components/Confirm'

  export default{
    components: {
      Toolbar,
      pageTurning,
      slideList,
      FilterView,
      Confirm
    },
    data () {
      var data = {}
      data.show = false
      data.timeoutStatus = false
      data.pinlei = '所有品类'
      data.pinpai = '所有品牌'
      data.pingtai = '所有平台'
      data.pingtaiId = ''
      data.saleUnit = ''
      data.startTime = ''
      data.endTime = ''
      data.filterButton = ''
      data.size10 = 0.19
      data.size12 = 0.23
      data.size13 = 0.25
      data.size14 = 0.27
      data.routeKey = ''
      data.defaultOrgId = ''
      data.defaultCategory = ''
      data.defaultCategoryId = ''
      data.filterOpenState = false
      data.viewTitle = ''
      data.showList = false
      // 渲染echarts需要用到的数据
      data.charts = []
      data.myChart = {}
      data.twoBarData11 = []
      data.twoBarData12 = []
      data.twoBarLegend1 = ['所选时期', '环比上期']
      data.twoBaryAxis1 = []
      data.twoBarData21 = []
      data.twoBarData22 = []
      data.twoBarLegend2 = ['所选时期', '环比上期']
      data.twoBaryAxis2 = []
      data.singleBarData1 = []
      data.singleBaryAxis1 = []
      data.singleBarData2 = []
      data.singleBaryAxis2 = []
      data.params = {
        mkey: '',
//        refresh: true,
        org_code: '',
        brand: '',
        brand_id: '',
        category_id: '',
        category: '',
        platform_id: '',
        platform: '',
        dateSeg: '',
        startTime: '',
        endTime: ''
      }
      data.modelMap = {}
      return data
    },
    methods: {
      reload: function () {
        window.location.reload()
      },
      goBack: function () {
//        window.history.back()
        this.show = true
      },
      onAction: function (value) {
        if (value === '确认') {
          window.cordova.exec(function (success) {
          }, function (error) {
            window.alert('Error: ' + error)
          }, 'MideaCommon', 'exit', [])
        }
      },
      doFilter: function () {
        this.$broadcast('doFilter')
      },
      showFilter: function (value) {
        this.filterButton = value
        this.filterOpenState = true
      },
      showSlideMenu: function () {
        this.showList = !this.showList
        var self = this
        setTimeout(function () {
          self.$broadcast('slideStart')
        }, 0)
      },
      getHttpData: function (httpUrl, params) {
        this.$http.post(httpUrl, params, {_timeout: 30000}).then((res) => {
          if (res.json().error) {
            this.timeoutStatus = true
            return
          }
          var data = res.json()
          this.defaultOrgId = data.org_code || ''
          this.defaultCategory = data.category || ''
          this.defaultCategoryId = data.category_id || ''
          this.pinlei = data.categoryCnd || data.category
          this.pinpai = data.brandCnd || data.brand
          this.pingtai = data.platformCnd || data.platform
          this.pingtaiId = data.platform_id || ''
          this.startTime = data.startTime || ''
          this.endTime = data.endTime || ''
          this.$broadcast('loadDataDone')
          document.getElementsByClassName('loading-box')[0].style.display = 'none'
          this.viewTitle = res.json().title  // 头部标题
          this.charts = res.json().chartDatas
          if (this.charts.length === 0) {
            return
          }
          // 第一个双柱图
//          if (this.charts[0].detail.length !== 0) {
          var oneBar = this.charts[0].detail
          var twoBaryAxis1 = []
          var twoBarData11 = []
          var twoBarData12 = []
          this.saleUnit = this.charts[0].saleUnit
          for (var a = 0; a < oneBar.length; a++) {
            twoBaryAxis1.push(oneBar[a].product_model)
            twoBarData11.push(oneBar[a].sales)
            twoBarData12.push(oneBar[a].qoq_sales)
            if (!this.modelMap.hasOwnProperty(oneBar[a].product_model)) {
              // 保存映射关系，方便点击事件触发
              this.modelMap[oneBar[a].product_model] = oneBar[a]
            }
          }
          this.twoBaryAxis1 = twoBaryAxis1
          this.twoBarData11 = twoBarData11
          this.twoBarData12 = twoBarData12
//          }
          // 第二个双柱图
//          if (this.charts[1].detail.length !== 0) {
          var twoBar = this.charts[1].detail
          var twoBaryAxis2 = []
          var twoBarData21 = []
          var twoBarData22 = []
          for (var b = 0; b < twoBar.length; b++) {
            twoBaryAxis2.push(twoBar[b].product_model)
            twoBarData21.push(twoBar[b].sales_amount)
            twoBarData22.push(twoBar[b].qoq_sales_amount)
            if (!this.modelMap.hasOwnProperty(twoBar[b].product_model)) {
              // 保存映射关系，方便点击事件触发
              this.modelMap[twoBar[b].product_model] = twoBar[b]
            }
          }
          this.twoBaryAxis2 = twoBaryAxis2
          this.twoBarData21 = twoBarData21
          this.twoBarData22 = twoBarData22
//          }
          // 第三个单柱图
//          if (this.charts[2].detail.length !== 0) {
          var threeBar = this.charts[2].detail
          var singleBaryAxis1 = []
          var singleBarData1 = []
          for (var c = 0; c < threeBar.length; c++) {
            singleBaryAxis1.push(threeBar[c].product_model)
            singleBarData1.push(threeBar[c].sales_growth)
            if (!this.modelMap.hasOwnProperty(threeBar[c].product_model)) {
              // 保存映射关系，方便点击事件触发
              this.modelMap[threeBar[c].product_model] = threeBar[c]
            }
          }
          this.singleBaryAxis1 = singleBaryAxis1
          this.singleBarData1 = singleBarData1
//          }
          // 第四个单柱图
//          if (this.charts[3].detail.length !== 0) {
          var fourBar = this.charts[3].detail
          var singleBaryAxis2 = []
          var singleBarData2 = []
          for (var d = 0; d < fourBar.length; d++) {
            singleBaryAxis2.push(fourBar[d].product_model)
            singleBarData2.push(fourBar[d].sales_amount_growth)
            if (!this.modelMap.hasOwnProperty(fourBar[d].product_model)) {
              // 保存映射关系，方便点击事件触发
              this.modelMap[fourBar[d].product_model] = fourBar[d]
            }
          }
          this.singleBaryAxis2 = singleBaryAxis2
          this.singleBarData2 = singleBarData2
//          }
          if (res.json().chartDatas.length === 0) {
            document.getElementsByClassName('competition-analysis-content')[0].style.display = 'none'
            document.getElementsByClassName('no-data')[0].style.display = 'block'
            return
          }
          setTimeout(function () {
            var htmlHeight = document.documentElement.clientHeight
            var toorBarHeight = document.getElementsByClassName('toolbar')[0].clientHeight
            var filterMessageBox = document.getElementsByClassName('filter-message-box')[0].clientHeight
            var tapHeight = document.getElementsByClassName('tab')[0].clientHeight
            var contentDiv = document.getElementsByClassName('competition-analysis-content')[0]
            contentDiv.style.height = htmlHeight - toorBarHeight - filterMessageBox - tapHeight + 'px'
          }, 0)
        }, (res) => {
          this.timeoutStatus = true
        })
      }
    },
    watch: {
      singleBarData2: function () {
        var that = this
        var twoBarOption1 = {
          legend: {
            data: this.twoBarLegend1,
            itemWidth: this.size10,
            itemHeight: this.size10,
            itemGap: 60,
            textStyle: {
              color: '#999',
              fontSize: this.size13
            }
          },
          tooltip: {
            trigger: 'axis',
            formatter: function (value) {
              return value[0].name.substring(0, 10) + '<br/>' + value[0].name.substring(10, value[0].name.length) + '<br/>' + value[0].seriesName + ': ' + value[0].value + that.saleUnit + '<br/>' + value[1].seriesName + ': ' + value[1].value + that.saleUnit
            },
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '8%',
            right: '13%',
            bottom: '6%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            splitNumber: 2,
            boundaryGap: [0, 0.01],
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              textStyle: {
                color: '#999',
                fontSize: this.size14
              }
            }
          },
          yAxis: {
            type: 'category',
            data: this.twoBaryAxis1,
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            triggerEvent: true,
            axisLabel: {
              textStyle: {
                color: '#999',
                fontSize: this.size14
              },
              formatter: function (value) {
                if (value.length > 10) {
                  return value.substring(0, 10) + '\n' + value.substring(10, value.length)
                } else {
                  return value
                }
              }
            }
          },
          series: [
            {
              name: this.twoBarLegend1[0],
              type: 'bar',
              barGap: 0,
              data: this.twoBarData11,
              barWidth: '20%'
            },
            {
              name: this.twoBarLegend1[1],
              type: 'bar',
              data: this.twoBarData12,
              barWidth: '20%'
            }
          ],
          color: ['#4A90E2', '#BCDBFF']
        }
        var twoBarOption2 = {
          legend: {
            data: this.twoBarLegend2,
            itemWidth: this.size10,
            itemHeight: this.size10,
            itemGap: 60,
            textStyle: {
              color: '#999',
              fontSize: this.size13
            }
          },
          tooltip: {
            trigger: 'axis',
            formatter: function (value) {
              return value[0].name.substring(0, 10) + '<br/>' + value[0].name.substring(10, value[0].name.length) + '<br/>' + value[0].seriesName + ': ' + value[0].value + '(万元)<br/>' + value[1].seriesName + ': ' + value[1].value + '(万元)'
            },
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '8%',
            right: '13%',
            bottom: '6%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            splitNumber: 2,
            boundaryGap: [0, 0.01],
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              textStyle: {
                color: '#999',
                fontSize: this.size14
              }
            }
          },
          yAxis: {
            type: 'category',
            data: this.twoBaryAxis2,
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            triggerEvent: true,
            axisLabel: {
              textStyle: {
                color: '#999',
                fontSize: this.size14
              },
              formatter: function (value) {
                if (value.length > 10) {
                  return value.substring(0, 10) + '\n' + value.substring(10, value.length)
                } else {
                  return value
                }
              }
            }
          },
          series: [
            {
              name: this.twoBarLegend2[0],
              type: 'bar',
              barGap: 0,
              data: this.twoBarData21,
              barWidth: '20%'
            },
            {
              name: this.twoBarLegend2[1],
              type: 'bar',
              data: this.twoBarData22,
              barWidth: '20%'
            }
          ],
          color: ['#4A90E2', '#BCDBFF']
        }
        var singleBarOption1 = {
          tooltip: {
            trigger: 'axis',
            formatter: function (value) {
              return value[0].name.substring(0, 10) + '<br/>' + value[0].name.substring(10, value[0].name.length) + '<br/>' + '增幅: ' + value[0].value + '%'
            },
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '8%',
            right: '13%',
            bottom: '-2%',
            top: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            splitNumber: 2,
            boundaryGap: [0, 0.01],
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: false
            },
            axisLabel: {
              show: false
            }
          },
          yAxis: {
            type: 'category',
            data: this.singleBaryAxis1,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: false
            },
            triggerEvent: true,
            axisLabel: {
              textStyle: {
                color: '#999',
                fontSize: this.size14
              },
              formatter: function (value) {
                if (value.length > 10) {
                  return value.substring(0, 10) + '\n' + value.substring(10, value.length)
                } else {
                  return value
                }
              }
            }
          },
          series: [
            {
              type: 'bar',
              data: this.singleBarData1,
              barWidth: 40,
              label: {
                normal: {
                  show: true,
                  position: 'right',
                  formatter: '{c}%',
                  textStyle: {
                    color: '#666'
                  }
                }
              }
            }
          ],
          color: ['#4A90E2', '#BCDBFF']
        }
        var singleBarOption2 = {
          tooltip: {
            trigger: 'axis',
            formatter: function (value) {
              return value[0].name.substring(0, 10) + '<br/>' + value[0].name.substring(10, value[0].name.length) + '<br/>' + '增幅: ' + value[0].value + '%'
            },
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '8%',
            right: '13%',
            bottom: '-2%',
            top: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            splitNumber: 2,
            boundaryGap: [0, 0.01],
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: false
            },
            axisLabel: {
              show: false
            }
          },
          yAxis: {
            type: 'category',
            data: this.singleBaryAxis2,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: false
            },
            triggerEvent: true,
            axisLabel: {
              textStyle: {
                color: '#999',
                fontSize: this.size14
              },
              formatter: function (value) {
                if (value.length > 10) {
                  return value.substring(0, 10) + '\n' + value.substring(10, value.length)
                } else {
                  return value
                }
              }
            }
          },
          series: [
            {
              type: 'bar',
              data: this.singleBarData2,
              barWidth: 40,
              label: {
                normal: {
                  show: true,
                  position: 'right',
                  formatter: '{c}%',
                  textStyle: {
                    color: '#666'
                  }
                }
              }
            }
          ],
          color: ['#B889FF', '#BCDBFF']
        }
        this.$nextTick(function () {
          // 返回的数据需要用echarts显示的
          var chartDomLength = document.getElementsByClassName('chartContainer').length
          var chartDomArray = new Array(chartDomLength)
          for (var x = 0; x < chartDomLength; x++) {
            chartDomArray[x] = document.getElementsByClassName('chartContainer')[x]
            this.myChart = window.Echarts.init(chartDomArray[x])
            if (x === 0) {
              this.myChart.setOption(twoBarOption1)
            } else if (x === 1) {
              this.myChart.setOption(twoBarOption2)
            } else if (x === 2) {
              this.myChart.setOption(singleBarOption1)
            } else if (x === 3) {
              this.myChart.setOption(singleBarOption2)
            }
            // 新增页面跳转
            this.myChart.on('click', (params) => {
              if (params.targetType === 'axisLabel') {
                let model = params.value
                if (that.modelMap.hasOwnProperty(model)) {
                  let product = that.modelMap[model]
                  let path = `/industry/productInfo?brand=${product.brand}&category_id=${that.defaultCategoryId}&category=${that.defaultCategory}&model=${product.model}&org_id=${that.defaultOrgId}`
                  that.$router.go(path)
                }
              }
            })
          }
        })
      }
    },
    events: {
      'filterConditions': function (filterConditions) {
        document.getElementsByClassName('loading-box')[0].style.display = 'block'
        if (filterConditions.brand !== '') {
          this.pinpai = filterConditions.brand
          this.pinpai = this.pinpai.replace(/,/g, '，')
        }
        if (filterConditions.platform !== '') {
          this.pingtai = filterConditions.platform
          this.pingtai = this.pingtai.replace(/,/g, '，')
        }
        this.params.org_code = filterConditions.org_code || ''
        this.params.brand = filterConditions.brand
        this.params.brand_id = filterConditions.brand_id
        this.params.category = filterConditions.category
        this.params.category_id = filterConditions.category_id
        this.params.platform = filterConditions.platform
        this.params.platform_id = filterConditions.platform_id
        this.params.dateSeg = filterConditions.dateSeg
        this.params.startTime = filterConditions.starttime
        this.params.endTime = filterConditions.endtime
        this.params.brand_all = filterConditions.brand_all
        this.params.mkey = this.routeKey
        this.getHttpData(this.httpUrl, this.params)
      }
    },
    created () {
      this.routeKey = 'competitionAnalysis'
      this.httpUrl = window.interface.indusPage
      var params = this.params
      params.mkey = this.routeKey
      this.getHttpData(this.httpUrl, params)
      var sizeBase = parseInt(document.documentElement.style.fontSize)
      this.size10 = sizeBase * this.size10
      this.size12 = sizeBase * this.size12
      this.size13 = sizeBase * this.size13
      this.size14 = sizeBase * this.size14
    },
    filters: {
      timeFilter: function (val) {
        if (val) {
          val = val.split('-')
          val = val.join('')
          return val
        }
      }
    },
    ready: function () {
    }
  }
</script>

<style lang="scss" scoped>
  .competition-analysis-content {
    position: relative;
    /*padding-top: 19vh;*/
    /*margin-bottom: 7.4vh;*/
    height: 80%;
    overflow: auto;
  }
  .filter-message-box{
    width: 100%;
    margin-top: 6.6vh;
    /*position: fixed;*/
    /*top: 6.6vh;*/
    /*left: 0;*/
    background: white;
    z-index: 101;
    font-size: 0.28rem;
    padding: 1.7vh 0 2.1vh .3rem;
    box-sizing: border-box;
    border-bottom: 1px solid rgb(238, 238, 238);
  }

  .filter-condition{
    margin-right: 0.2rem;
    margin-top: 1.1vh;
    font-size: 0.24rem;
    float: left;
    color: #4A90E2;
    padding: 0.35vh 1.2vh;
    box-sizing: border-box;
    border: 1px solid #4A90E2;
    background: #FAFCFF;
    border-radius: 3px;
    max-width: 85%;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
  }

  .title-time {
    padding: 2.4vh 0 1.3vh 0;
    border-bottom: 1px solid #eeeeee;
    box-sizing: border-box;
  }

  .title {
    font-size: .32rem;
    background: url('../../../../static/img/time-title.png') no-repeat center right;
    background-position: .3rem center;
    background-size: .28rem .26rem;
    padding-left: .7rem;
    /*height: 3.3vh;*/
    /*line-height: 3.3vh;*/
    color: #333333;
  }

  .important {
    margin: 1.5vh 0;
    font-size: .28rem;
    padding-left: .3rem;
    color: #666666;
  }

  .division0, .division1, .division2 {
    width: 100%;
    height: 1.5vh;
    background: rgb(238, 238, 238);
  }

  .chartContainer0, .chartContainer1 {
    width: 100%;
    height: 67.47vh;
  }

  .chartContainer2, .chartContainer3 {
    width: 100%;
    height: 59.94vh;
  }

  .btnPage {
    position: fixed;
    left: 0;
    top: 50vh;
    width: 100%;
    z-index: 200;
  }

  .btn-previous {
    width: 0.4rem;
    height: 0.8rem;
    float: left;
    background: rgba(0, 0, 0, 0.2);
  }

  .btn-next {
    width: 0.4rem;
    height: 0.8rem;
    float: right;
    background: rgba(0, 0, 0, 0.2);
  }

  .leftButton {
    width: .5rem;
    height: 100%;
    background: url('../../../../static/img/btn-back.png') no-repeat center right;
    background-size: 100%;
  }
</style>
